import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
    FlatList,
    SafeAreaView,
    Platform,
    DeviceEventEmitter,
    BackHandler,
} from 'react-native';
import ScrollableTabView, { DefaultTabBar } from 'react-native-scrollable-tab-view';
import { RRCLoading, RRCToast } from 'react-native-overlayer';
import HttpUtil from '../util/HttpUtil';
import BaseComponent from '../component/BaseComponent';
import InventoryNormal from '../component/InventoryNormal';
import InventoryDiff from '../component/InventoryDiff';
import InventorySurplus from '../component/InventorySurplus';
import InventoryLoss from '../component/InventoryLoss';
import { queryInventoryDetail } from '../util/RealmUtil';
//import KeyEvent from 'react-native-keyevent';

import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';

let that = {};

export default class ViewInventoryDetail extends BaseComponent {

    constructor(props) {
        super(props);
        this.state = {
            tab: 0,
            detail: {},
            normal: [],
            diff: [],
            surplus: [],
            loss: [],
        }
        that = this;
    }

    componentDidMount() {
        RRCLoading.setLoadingOptions({
            text: '加载中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: { backgroundColor: 'rgba(0,0,0,0.8)' },
            loadingTextStyle: {}
        })
        RRCLoading.show();
        this.fetchData();
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener("hardwareBackPress", this.onBackClicked);
        }
    }

    onBackClicked = () => {
        this.props.navigation.navigate('Inventory');
        this.props.navigation.state.params.callBack();
        return true;
    }

    back = () => {
        this.props.navigation.navigate('Inventory');
        this.props.navigation.state.params.callBack();
    }



    fetchData = () => {
        if (global.variables.useMode == 1) {
            this.fetchDataFromLocal();
        } else {
            this.fetchDataFromServe();
        }
    }

    fetchDataFromLocal = () => {
        const { params } = this.props.navigation.state;
        const id = params ? params.id : null;
        queryInventoryDetail(id).then(result => {
            RRCLoading.hide();
            console.log(JSON.stringify(result));
            if (result) {
                let normal = [], diff = [], surplus = [], loss = [];
                result.detailList.forEach(value => {
                    if (value.status == 2) {
                        diff.push(value);
                    } else if (value.status == 3) {
                        normal.push(value);
                    } else if (value.status == 4) {
                        loss.push(value);
                    } else if (value.status == 5) {
                        surplus.push(value);
                    }
                });
                if (result.moreOutList && result.moreOutList.length > 0) {
                    this.setState({
                        surplus: result.moreOutList
                    })
                }
                this.setState({
                    detail: result,
                    normal: normal,
                    diff: diff,
                    //surplus:surplus,
                    loss: loss
                });
            }
        }).catch(error => {
            RRCLoading.hide();
            RRCToast.show('系统异常', 1, 7000);
        })
    }

    fetchDataFromServer = () => {
        const { params } = this.props.navigation.state;
        const id = params ? params.id : null;
        let args = {
            sheetId: id,
        }
        //console.log(id);
        HttpUtil.post('inventoryData', args)
            .then(result => {
                if (result.httpCode == 200) {
                    console.log(JSON.stringify(result.data));
                    let normal = [], diff = [], surplus = [], loss = [];
                    result.data.detailList.forEach(value => {
                        if (value.status == 2) {
                            diff.push(value);
                        } else if (value.status == 3) {
                            normal.push(value);
                        } else if (value.status == 4) {
                            loss.push(value);
                        } else if (value.status == 5) {
                            surplus.push(value);
                        }
                    });
                    if (result.data.moreOutList && result.data.moreOutList.length > 0) {
                        this.setState({
                            surplus: result.data.moreOutList
                        })
                    }
                    this.setState({
                        detail: result.data,
                        normal: normal,
                        diff: diff,
                        //surplus:surplus,
                        loss: loss
                    });
                    //console.log(inventoryed);
                    RRCLoading.hide();
                } else {
                    RRCLoading.hide();
                    RRCToast.show('系统异常', 1, 7000);
                }
            })
            .catch(error => {
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 7000);
            })
    }


    changeTab = (i) => {
        this.scrollableTabView.goToPage(i);
        this.setState({
            tab: i,
        });
    }


    renderTabBar() {
        return (
            <View style={styles.detail}>
                <TouchableOpacity onPress={() => this.changeTab(0)}>
                    <View style={styles.detailBox}>
                        <Text style={[styles.detailNum, this.state.tab == 0 ? { color: 'blue' } : { color: '#000' },]}>{this.state.normal.length}</Text>
                        <Text style={styles.detailName}>正常</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => this.changeTab(1)}>
                    <View style={styles.detailBox}>
                        <Text style={[styles.detailNum, this.state.tab == 1 ? { color: 'blue' } : { color: '#000' },]}>{this.state.diff.length}</Text>
                        <Text style={styles.detailName}>差异</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => this.changeTab(2)}>
                    <View style={styles.detailBox}>
                        <Text style={[styles.detailNum, this.state.tab == 2 ? { color: 'blue' } : { color: '#000' },]}>{this.state.surplus.length}</Text>
                        <Text style={styles.detailName}>盘盈</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => this.changeTab(3)}>
                    <View style={[styles.detailBox, { marginRight: getPixel(0) }]}>
                        <Text style={[styles.detailNum, this.state.tab == 3 ? { color: 'blue' } : { color: '#000' },]}>{this.state.loss.length}</Text>
                        <Text style={styles.detailName}>盘亏</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }

    render() {
        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.header}>
                    <View style={{ width: getPixel(40), justifyContent: 'center', alignItems: 'center' }}>
                        <TouchableOpacity onPress={() => this.back()}>
                            <Image source={require('../images/back.png')} style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                        </TouchableOpacity>
                    </View>

                    <View style={{ width: getScreenWidth() - getPixel(80), justifyContent: 'center', alignItems: 'center' }}>
                        <Text style={{ fontSize: getPixel(17), color: '#333' }}>资产盘点</Text>
                    </View>
                    <View style={{ width: getPixel(40), justifyContent: 'center', alignItems: 'center' }}>
                    </View>
                </View>
                <View style={{ paddingLeft: getPixel(15), paddingRight: getPixel(15), paddingBottom: getPixel(20), paddingTop: getPixel(10), backgroundColor: '#FFF' }}>
                    <View style={styles.title}>
                        <View style={{ alignItems: 'center' }}>
                            <Text style={styles.titleText}>{this.state.detail.inventorySheetName}</Text>
                        </View>
                        {/* <TouchableOpacity onPress={this.submit}>
                            <View style={{ width: getPixel(95), alignItems: 'center' }}>
                                <Text style={styles.stateFinish}>保存结果</Text>
                            </View>
                        </TouchableOpacity> */}
                    </View>
                </View>
                <View style={styles.info}>
                    <View style={styles.infoText}>
                        <Text style={styles.infoTextTable}>
                            创建人：{this.state.detail.createName}
                        </Text>
                        <Text style={styles.infoTextTable}>
                            盘点总数：{this.state.detail.totalCount}
                        </Text>
                    </View>
                    <View style={styles.infoText}>
                        <Text style={styles.infoTextTable}>
                            创建日期：{this.state.detail.createTimeString}
                        </Text>
                        <Text style={styles.infoTextTable}>
                            完成日期：{this.state.detail.endTimeString}
                        </Text>
                    </View>

                </View>
                <ScrollableTabView
                    ref={(ref) => { this.scrollableTabView = ref; }}
                    renderTabBar={() => this.renderTabBar()}
                    initialPage={0}
                    onChangeTab={({ i, from }) => {
                        this.setState({
                            tab: i,
                        });
                    }}
                >
                    <InventoryNormal detailList={this.state.normal} />
                    <InventoryDiff detailList={this.state.diff} />
                    <InventorySurplus detailList={this.state.surplus} />
                    <InventoryLoss detailList={this.state.loss} />
                </ScrollableTabView>
            </SafeAreaView>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
    },
    header: {
        height: getPixel(50),
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
        flexDirection: 'row',
    },
    title: {
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: '#EEE',
        borderBottomWidth: getPixel(1),
        paddingBottom: getPixel(10),
    },
    titleText: {
        fontSize: getPixel(16),
        color: '#333',
        width: getScreenWidth() - getPixel(115),
    },
    stateStart: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        backgroundColor: '#FFAA2E',
        color: '#FFF',
        borderRadius: getPixel(5),
        paddingLeft: getPixel(28),
        paddingRight: getPixel(28),
        width: getPixel(180),
        height: getPixel(30),
    },
    stateFinish: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        backgroundColor: '#4A69DD',
        color: '#FFF',
        borderRadius: getPixel(5),
    },
    inventoryed: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        backgroundColor: '#FFAA2E',
        color: '#FFF',
        borderRadius: getPixel(5),
        paddingLeft: getPixel(8),
        paddingRight: getPixel(8),
    },
    uninventory: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        backgroundColor: '#4A69DD',
        color: '#FFF',
        borderRadius: getPixel(5),
        paddingLeft: getPixel(8),
        paddingRight: getPixel(8),
    },
    info: {
        justifyContent: 'center',
        marginTop: getPixel(10),
        backgroundColor: '#FFF',
        paddingBottom: getPixel(10),
        paddingTop: getPixel(10),
    },
    infoText: {
        flexDirection: 'row',
        alignItems: 'center',
        height: getPixel(30),
        marginLeft: getPixel(15),
    },
    infoTextTable: {
        fontSize: getPixel(14),
        color: '#999',
        width: getScreenWidth() / 2,
    },
    detail: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    detailBox: {
        width: getScreenWidth() / 4 - getPixel(10),
        height: getScreenWidth() / 4 - getPixel(10),
        backgroundColor: '#FAFAFA',
        marginRight: getPixel(1),
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: getPixel(4),
    },
    detailName: {
        color: '#999',
        paddingTop: getPixel(10),
        fontSize: getPixel(14),
    },
    detailNum: {
        color: '#000',
        fontSize: getPixel(16),
    },
    buttonGroup: {
        flexDirection: 'row',
        paddingLeft: getPixel(15),
        paddingRight: getPixel(15),
        height: getPixel(60),
        backgroundColor: '#FFF',
        width: getScreenWidth(),
        alignItems: 'center',
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
    },
    buttonSearch: {
        backgroundColor: '#6484FA',
        height: getPixel(40),
        borderRadius: getPixel(10),
        width: (getScreenWidth() - 30),
    },
    buttonSave: {
        backgroundColor: '#4a69dd',
        height: getPixel(40),
        borderTopRightRadius: getPixel(10),
        borderBottomRightRadius: getPixel(10),
        width: (getScreenWidth() - 30) / 2,
    },
    cardTitle: {
        flexDirection: 'row',
        borderBottomColor: '#EEEEEE',
        borderBottomWidth: getPixel(1),
    },
    cardInfo: {
        flexDirection: 'row',
        marginTop: getPixel(10),
    },
    assetTag: {
        width: getScreenWidth() - getPixel(110),
        height: getPixel(60),
        justifyContent: 'center',
    },
    assetInfo: {
        width: getScreenWidth() - getPixel(130),
        height: getPixel(130),
        justifyContent: 'center',
    },
    assetImg: {
        width: getPixel(100),
        height: getPixel(130),
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    assetInfoBasic: {
        justifyContent: 'center',
    },
    assetInfoOther: {
        justifyContent: 'center',
    },
    assetInfoOtherText: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    assetInfoBasicOwner: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    assetInfoBasicDept: {
        fontSize: getPixel(12),
        color: '#FFAA2E',
        backgroundColor: '#FFF9EF',
        borderColor: '#FFAA2E',
        borderWidth: 1,
        padding: getPixel(2),
        paddingLeft: getPixel(4),
        marginLeft: getPixel(5),
        height: getPixel(20),
    },
    img: {
        resizeMode: 'contain',
        width: getPixel(100),
        height: getPixel(100),
    },
    assetState: {
        width: getPixel(80),
        height: getPixel(60),
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    assetStateText: {
        fontSize: getPixel(14),
        width: getPixel(60),
        height: getPixel(30),
        borderColor: '#58CEB6',
        borderWidth: 1,
        textAlign: 'center',
        lineHeight: getPixel(30),
        color: '#58CEB6',
        backgroundColor: '#EEFFFC',
        borderRadius: 10,
    },
});